package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    /**
     * 批量插入预约数据
     * @param orderSettingList
     */
    @Override
    public void add(List<OrderSetting> orderSettingList) {
        if (orderSettingList !=null && orderSettingList.size()>0){
            for (OrderSetting orderSetting:orderSettingList){
//                1.先查有无数据--通过日期
             OrderSetting os= orderSettingDao.findOrderSettingByOrderDate(orderSetting.getOrderDate());
             if (os==null){
//                2. 日期为空--则插入数据
                 orderSettingDao.add(orderSetting);
             }
             else if (os.getNumber()!=orderSetting.getNumber()){
//                3.  根据日期修改预约人数--则更新数据
                 orderSettingDao.update(orderSetting);
             }
            }
        }
    }

    /**
     * 根据日期范围--查找预约数据
     * @param date --2017-5
     * @return
     */
    @Override
    public List<Map> findAllOrderSettingByBate(String date) {
//        多条件查询使用map集合
        String begin=date+"-"+"1";
        String end=date+"-"+"31";
        HashMap<String,Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("end", end);
//        查找返回预约数据
        List<OrderSetting> orderSettingList=orderSettingDao.findAllOrderSettingByBate(map);
//            返回数据
        List<Map> data = new ArrayList<>();
        for (OrderSetting orderSetting:orderSettingList){
//            转换数据
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("date", orderSetting.getOrderDate().getDate());
//            System.out.println(orderSetting.getOrderDate());
            dataMap.put("number", orderSetting.getNumber());
            dataMap.put("reservations", orderSetting.getReservations());
            data.add(dataMap);
        }
        return data;
    }

    /**
     * 根据日期修改预约人数
     * @param orderSetting
     */
    @Override
    public void updateOrderSettingNumber(OrderSetting orderSetting) {
        OrderSetting os= orderSettingDao.findOrderSettingByOrderDate(orderSetting.getOrderDate());
//        根据日期修改预约人数
        if (os==null){
//              插入预约设置数据
            orderSettingDao.add(orderSetting);
        }else {
            orderSettingDao.update(orderSetting);
        }
    }

    //定时清理上一个月的ordersetting数据
    public void clearOrderSetting(String today) {
        orderSettingDao.clearOrderSetting(today);
    }
}
